from django.forms import ModelForm,ModelChoiceField
from django import forms

from xadmin.models import Article
from xadmin.models import Node


def node_order_tree(n_list, top_list, node_list):
    '''
    按照第一个顶级栏目子栏目第二个顶级栏目子栏目...这样排序, 显示文章的栏目结构
    :param n_list: 返回的栏目列表
    :return:
    '''
    for id in top_list:
        node = Node.objects.get(id=id)
        n_list.append(node)
        s_node_set = Node.objects.filter(parent_node_id=node.id, id__in=node_list, is_active=True)
        s_node_list = [x.id for x in s_node_set]

        node_order_tree(n_list, s_node_list, node_list)

    return n_list

def GetNodeTree():
    node_queryset = Node.objects.filter(node_type='content')
    node_list = []
    top_list = []
    for n in node_queryset:
        if n.node_level == 1:
            top_list.append(n.id)
        else:
            node_list.append(n.id)
            i = 0
            for nn in n.node_path.split(','):
                if i == 0:
                    top_list.append(int(nn))
                else:
                    node_list.append(int(nn))
                i = i + 1

    top_list = set(top_list)
    node_list = set(node_list)
    node_trees = node_order_tree([], top_list, node_list)
    return node_trees


def get_queryset():
    order_list = GetNodeTree()
    id_list = [n.id for n in order_list]
    ordering = 'FIELD(`id`, %s)' % ','.join(str(id) for id in id_list)
    queryset = Node.objects.filter(id__in=id_list).extra(select={'ordering': ordering}, order_by=('ordering',))
    return queryset



class ArticleForm(ModelForm):
    parent_node = ModelChoiceField(label='父栏目', required=True, queryset=get_queryset())
    class Meta:
        model = Article
        exclude = ('site', 'order_num', 'is_delete')

    def __init__(self, *args, **kwargs):
        super(ArticleForm, self).__init__(*args, **kwargs)

        no_style_colum = ('content', 'is_active', 'is_search')
        self.fields['parent_node'].queryset = get_queryset()
        for field_name in self.fields:
            field = self.fields[field_name]
            if field_name not in no_style_colum:
                field.widget.attrs.update({'class': 'form-control'})
            if field_name == 'add_time':
                field.widget.attrs.update({'placeholder': 'yyyy/MM/dd HH:mm:ss'})
